package com.xc.jwt;

import com.xc.domain.pojo.User;
import com.xc.domain.service.IUserService;
import com.xc.exception.BusinessException;
import com.xc.vo.ResultVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RequestMapping("/test")
@RestController
@Slf4j
@Tag(name = "测试登录")
@RequiredArgsConstructor
public class LoginTest {

    private final IUserService userService;
    @Autowired
    private  JwtProperties jwtProperties;

    @PostMapping("/login")
    @Operation(summary = "登录")
    public ResultVO<LoginVO> login(@RequestBody User user) {
        User loginUser = userService.lambdaQuery()
                .eq(user.getId() != null, User::getId, user.getId())
                .eq(StringUtils.hasText(user.getUsername()), User::getUsername, user.getUsername())
                .eq(StringUtils.hasText(user.getPassword()), User::getPassword, user.getPassword())
                .one();
        if (loginUser == null) {
            throw new BusinessException(9999, "用户不存在");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("id", user.getId());
        map.put("userName", user.getUsername());
        String jwt = JwtUtils.createJwt(jwtProperties.getSign(), jwtProperties.getSecret(), map, jwtProperties.getExpiration());
        return ResultVO.success(LoginVO.builder()
                .id(user.getId())
                .jwt(jwt)
                .build());
    }
}
